/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.infor.entity.BudgetExpen;
import com.jeeplus.modules.infor.entity.HandlingExpense;
import com.jeeplus.modules.infor.entity.StoreBudget;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.Handling;
import com.jeeplus.modules.infor.service.HandlingService;

/**
 * 装卸收支明细Controller
 * @author 李超辉
 * @version 2019-02-14
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/handling")
public class HandlingController extends BaseController {

	@Autowired
	private HandlingService handlingService;

	@Autowired
	private SlService slService;
	
	@ModelAttribute
	public Handling get(@RequestParam(required=false) String id) {
		Handling entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = handlingService.get(id);
		}
		if (entity == null){
			entity = new Handling();
		}
		return entity;
	}
	
	/**
	 * 装卸收支明细列表页面
	 */
	@RequiresPermissions("infor:handling:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/handlingList";
	}
	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/infor/4/handlingList";
	}
	/**
	 * 装卸收支明细列表页面
	 */

	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/infor/5/handlingList";
	}
	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/infor/3/handlingList";
	}

	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/infor/2/handlingList";
	}

	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = {"list5"})
	public String list5() {
		return "modules/infor/1/handlingList";
	}

	/**
	 * 装卸收支明细列表页面
	 */
	@RequestMapping(value = {"list6"})
	public String list6() {
		return "modules/infor/6/handlingList";
	}
		/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:handling:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Handling handling, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			handling.setPro(pro);
		}
		Page<Handling> page = handlingService.findPage(new Page<Handling>(request, response), handling);
		return getBootstrapData(page);
	}
	/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Handling handling, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			handling.setPro(pro);
		}
		handling.setDjzt("已确认");
		Page<Handling> page = handlingService.findPage(new Page<Handling>(request, response), handling);
		return getBootstrapData(page);
	}

	/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(Handling handling, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			handling.setPro(pro);
		}
		handling.setDjzt("已确认");
		Page<Handling> page = handlingService.findPage1(new Page<Handling>(request, response), handling);
		return getBootstrapData(page);
	}

	/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(Handling handling, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			handling.setPro(pro);
		}
		handling.setDjzt("已确认");
		Page<Handling> page = handlingService.findPage2(new Page<Handling>(request, response), handling);
		return getBootstrapData(page);
	}

	/**
	 * 装卸收支明细列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(Handling handling, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			handling.setPro(pro);
		}
		handling.setDjzt("已确认");
		Page<Handling> page = handlingService.findPage3(new Page<Handling>(request, response), handling);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑装卸收支明细表单页面
	 */
	@RequiresPermissions(value={"infor:handling:view","infor:handling:add","infor:handling:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Handling handling, Model model) {
		if(handling.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			if(!pro.equals("总部")){
				handling.setPro(pro);
			}
			handling.setBsc(UserUtils.getbsc());
			handling.setDjzt("已创建");
			handling.setKpzt("未开票");
			handling.setJszt("未结算");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Handling p=new Handling();
			p.setDjh(code);
			List<Handling> l=handlingService.findList(p);
			if(l==null||l.size()<1){
				handling.setDjh(code+"001"+"ZXSZ");
			}else{
				if(l.size()/10==0){
					handling.setDjh(code+"00"+(l.size()+1)+"ZXSZ");
				}else
				if(l.size()/100==0){
					handling.setDjh(code+"0"+(l.size()+1)+"ZXSZ");
				}else{handling.setDjh(code+(l.size()+1)+"ZXSZ");}

			}
		}
		model.addAttribute("handling", handling);
		return "modules/infor/handlingForm";
	}

	/**
	 * 保存装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:handling:add","infor:handling:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Handling handling, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, handling)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		List<HandlingExpense>  l=handling.getHandlingExpenseList();
		double e=0.0;
		for(HandlingExpense b:l){
			if(b.getType().equals("罚款")){
				e+=Double.parseDouble(b.getJe());
			}
		}
		handling.setFk(e+"");
		//新增或编辑表单保存
		handling.setYf("0");
		handling.setWf(handling.getZzc());
		handlingService.save(handling);//保存
		j.setSuccess(true);
		j.setMsg("保存装卸收支明细成功");
		return j;
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(Handling handling, RedirectAttributes redirectAttributes) {
		DecimalFormat df = new DecimalFormat("0.00%");
		AjaxJson j = new AjaxJson();
		handling.setDjzt("已确认");
		Sl sl=slService.findUniqueByProperty("pro",handling.getPro());
		sl=slService.get(sl.getId());
		double sj=Double.parseDouble(handling.getZsr())*Double.parseDouble(sl.getSl());
		double mlr=Double.parseDouble(handling.getZsr())-Double.parseDouble(handling.getZzc())-sj;
		double lrl=mlr/Double.parseDouble(handling.getZsr());
		handling.setSj(sj+"");
		handling.setMlr(mlr+"");
		handling.setLrl(df.format(lrl));
		handling.setZzsl(sl.getSl());
		handlingService.save(handling);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 付款
	 */
	@ResponseBody
	@RequestMapping(value = "fk")
	public String fk(Handling handling, String fph,String fkrq, RedirectAttributes redirectAttributes) throws ParseException {
		NumberFormat nf = NumberFormat.getInstance();
		handling.setJszt("已结算");
		handling.setZckpje(handling.getZzc());
		handling.setZcfph(fph);
		handling.setYf(handling.getZzc());
		SimpleDateFormat bf = new SimpleDateFormat("yyyy-MM-dd");
		handling.setFkrq(bf.parse(fkrq));
			handling.setJszt("已结算");

		handlingService.save(handling);

		return "";
	}
	/**
	 * 确认仓租收支明细
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public AjaxJson qxqr(Handling handling, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		handling.setDjzt("已创建");
		handlingService.save(handling);
		j.setMsg("取消确认成功");
		return j;
	}
	/**
	 * 删除装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:handling:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Handling handling, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		handlingService.delete(handling);
		j.setMsg("删除装卸收支明细成功");
		return j;
	}
	
	/**
	 * 批量删除装卸收支明细
	 */
	@ResponseBody
	@RequiresPermissions("infor:handling:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			handlingService.delete(handlingService.get(id));
		}
		j.setMsg("删除装卸收支明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:handling:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Handling handling, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "装卸收支明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Handling> page = handlingService.findPage(new Page<Handling>(request, response, -1), handling);
    		new ExportExcel("装卸收支明细", Handling.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出装卸收支明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Handling detail(String id) {
		return handlingService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:handling:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Handling> list = ei.getDataList(Handling.class);
			for (Handling handling : list){
				try{
					handlingService.save(handling);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条装卸收支明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条装卸收支明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入装卸收支明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/handling/?repage";
    }
	
	/**
	 * 下载导入装卸收支明细数据模板
	 */
	@RequiresPermissions("infor:handling:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "装卸收支明细数据导入模板.xlsx";
    		List<Handling> list = Lists.newArrayList(); 
    		new ExportExcel("装卸收支明细数据", Handling.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/handling/?repage";
    }
	

}